import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../routes/app_pages.dart';
import '../../../utils/common/app_manager.dart';
import '../../../utils/common/base_controller.dart';
import '../../../utils/widget/common.dart';
import '../request/user_request.dart';


class LoginController extends BaseController {
  final model = BaseModel.fromJson({}).obs;
  final models = <BaseModel>[].obs;
  final checkList = <BaseModel>[].obs;

  // 账号
  final TextEditingController accountVC = TextEditingController();
  // 密码
  final TextEditingController passwordVC = TextEditingController();
  // 验证码
  final TextEditingController shortCodeVC = TextEditingController();
  final TextEditingController hostVC = TextEditingController();

  late TextField accountTextField;
  late TextField passwordTextField;
  late TextField shortCodeTextField;

  //可以获取验证码
  final canLogin = false.obs;
  final checkboxSelected = false.obs;

  @override
  void onInit() {
    super.onInit();

  }


  loginClick() {
    closeKeyboard();
    Get.toNamed(Routes.HOME);
    return;
    if(accountVC.text == "") {
      showMessage("请输入账号或手机号");
      return;
    }
    if(passwordVC.text == "") {
      showMessage("请输入密码");
      return;
    }
    // if(!checkboxSelected){
    //   showMessage("请先阅读与同意《服务协议》和《隐私协议》");
    //   return;
    // }
    gotoLoginWithPassword(accountVC.text, passwordVC.text);
  }


  // 密码登录
  gotoLoginWithPassword(String account, String password) {
    if (AppManager.userToken.isNotEmpty) {
      _loginWitPassword(account, password);
    }else {
      debugPrint("AppManager.userToken = null");
      debugPrint("正在获取 UserToken...");
      showLoadingMessage("正在获取token...");
      UserRequest.getUserToken(AppManager.uuid).then((result) {
        if (result.success && AppManager.userToken.isNotEmpty) {
          _loginWitPassword(account, password);
        }else {
          dismissLoading();
          _loginWitPassword(account, password);
        }
      });
    }
  }


  _loginWitPassword(String account, String password) {
    showLoadingMessage("拼命登录中...");
    UserRequest.loginWithPassword(account: account, password: password).then((result) {
      if (result.success) {
        AppManager.setUserAccountJson(result.data);
        localStorageWrite("native_auth", true);
        localStorageWrite("lastAccountPassword", password);
        // getShopListAndHomeData();
      }else if (result.code == "10102") {
        dismissLoading();
        gotoLoginWithPassword(account, password);
      }else {
        dismissLoading();
      }
    });
  }

  checkboxClick(bool? value) {
    closeKeyboard();
    checkboxSelected.value = value!;
    canLogin.value = (accountVC.text.isNotEmpty &&
        passwordVC.text.length >= 6
        && checkboxSelected.value == true) ? true : false;
  }

}